<template>
    <div class="goods-add-form">
        <div class="section">
            <h2 class="section-title">基础信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="sales_Return" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="销售退货编号" style="margin-bottom: 30px;">
                            <el-input v-model="sales_Return.sale_Return_Code" placeholder="自动获取编号" disabled />
                        </el-form-item>
                        <el-form-item label="客户名称" style="margin-bottom: 30px;">
                            <el-input v-model="sales_Return.customer_Name" placeholder="客户名称" disabled />
                        </el-form-item>
                        <el-form-item label="联系方式" prop="sale_order_sign_time" style="margin-bottom: 30px;">
                            <el-input v-model="sales_Return.contacts_Phone" placeholder="联系方式" disabled />
                        </el-form-item>
                        <el-form-item prop="warehouse_code" label="入库仓库" style="margin-bottom: 30px;">
                            <el-select v-model="sales_Return.warehouse_code" placeholder="请选择入库仓库"
                                @change="handleSelectChange">
                                <el-option v-for="item in Weahouse" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="sale_Return_Dept_Id" label="入库出库部门" style="margin-bottom: 30px;">
                            <el-tree-select v-model="sales_Return.sale_Return_Dept_Id" :data="deptOptions"
                                :props="defaultProps" :check-strictly="true" placeholder="请选择入库部门" @change="getUser()">
                                <template #header>
                                    <el-input v-model="deptName" placeholder="搜索入库部门" style="padding: 5px"
                                        @input="getDeptDebounced" />
                                </template>
                            </el-tree-select>
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                        <el-form-item label="销售订单" prop="sale_Order_Name" style="margin-bottom: 30px;">
                            <el-input v-model="sales_Return.sale_Order_Name" placeholder="请点击查询销售订单" clearable readonly
                                class="order-input" @click="showOrderDialog">
                                <template #append>
                                    <el-button icon="Search" @click="showOrderDialog" />
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="联系人" style="margin-bottom: 30px;">
                            <el-input v-model="sales_Return.contacts_Name" placeholder="联系人" disabled />
                        </el-form-item>
                        <el-form-item label="入库日期" style="margin-bottom: 30px;" prop="sale_Return_Store_Time">
                            <el-date-picker v-model="sales_Return.sale_Return_Store_Time" type="date" :editable="false"
                                placeholder="请选择入库日期" :size="size" style="width: 460px;"
                                value-format="YYYY-MM-DDTHH:mm:ss.SSSZ" />
                        </el-form-item>
                        <el-form-item prop="zone_code" label="入库库区" style="margin-bottom: 30px;">
                            <el-select v-model="sales_Return.zone_code" placeholder="请选择入库库区" @change="handleSzone">
                                <el-option v-for="item in Warhouse_zone" :key="item.zone_code" :label="item.zone_name"
                                    :value="item.zone_code" />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="sale_Return_Rep_Id" label="入库员" style="margin-bottom: 30px;">
                            <el-select v-model="sales_Return.sale_Return_Rep_Id" placeholder="请选择入库员">
                                <template #header>
                                    <el-input v-model="userName" placeholder="搜索入库员" style="padding: 5px"
                                        @input="getUserDebounced" />
                                </template>
                                <el-option v-for="item in userOptions" :key="item.user_id" :label="item.user_name"
                                    :value="item.user_id" />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
                <el-form-item label="退货原因" prop="sale_Return_Reason">
                    <el-input v-model="sales_Return.sale_Return_Reason" placeholder="退货原因" />
                </el-form-item>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">销售产品明细</h2>
            <div style="float: left;margin: 10px 0px;">
                <el-button type="primary" @click="detailstAdd">添加</el-button>
                <el-button @click="productDel">移除</el-button>
            </div>
            <el-table :data="selectedDetailsData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="pro_name" label="产品名称" width="130" />
                <el-table-column prop="pro_code" label="产品编号" width="160" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="pro_model" label="规格型号" />
                <el-table-column prop="measure_id" label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.measure_id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="pro_sale_qty" label="销售数量" />
                <el-table-column prop="pro_outbound_qty" label="已出库" />
                <el-table-column prop="unshipped_qty" label="未出库" />
                <el-table-column prop="pro_Return_Qty" label="本次退货数量" width="120px">
                    <template #default="scope">
                        <el-input v-model="scope.row.pro_Return_Qty" style="width: 75px" :precision="2" :min="0" />
                    </template>
                </el-table-column>
                <el-table-column prop="pro_sale_price" label="销售单价" />
                <el-table-column prop="pro_Return_Price" label="退货金额" />
                <!-- <el-table-column prop="address" label="出库库位">
                    <template #default="scope">
                        <el-select v-model="scope.row.location_code" placeholder="选择库位" size="small"
                            @change="(val) => handleLocationChange(val, scope.row)">
                            <el-option v-for="item in Warehouse_location" :key="item.location_code"
                                :label="item.location_name" :value="item.location_code" />
                        </el-select>
                    </template>
                </el-table-column> -->
            </el-table>
            <div style="height: 40px; line-height: 40px;">
                <div style="display: inline-block; float: left;">合计</div>
                <div style="display: inline-block; float:right">退货总数量：{{ sale_return_total_qty }} &nbsp;&nbsp;&nbsp;
                    退货总金额：{{
                        pro_return_total_price }} &nbsp;&nbsp;&nbsp;
                    订单状态：{{ return_status }}
                </div>
            </div>
        </div>

        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <el-dialog v-model="proSaleTableVisible" width="970" title="添加销售订单">
        <hr>
        <div style="margin: 10px 0px;">
            <div style="float: left;margin: 10px 0px;">
                <el-input v-model="orderCode" style="width: 240px;margin-right: 20px;" placeholder="请输入销售编号" />
                <el-select v-model="orderStatus" placeholder="请选择单据状态" @change="customerEndit"
                    style="width: 240px;margin-right: 20px;">
                    <el-option v-for="item in statusOpt" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-select v-model="customerName" placeholder="请选择客户" @change="customerEndit" style="width: 240px;">
                    <template #header>
                        <el-input v-model="customer_Name" placeholder="搜索客户" style="padding: 5px"
                            @input="getCustomerDebounced" />
                    </template>
                    <el-option v-for="item in customerOptons" :key="item.customer_code" :label="item.customer_name"
                        :value="item.customer_code" />
                </el-select>
            </div>
            <div style="float: left;margin: 10px 0px;">
                <el-select v-model="repId" placeholder="请选择出库员" style="width: 240px;margin-right: 20px;">
                    <template #header>
                        <el-input v-model="user_name" placeholder="搜索出库员" style="padding: 5px;"
                            @input="userFillDebounced" />
                    </template>
                    <el-option v-for="item in userOpt" :key="item.user_id" :label="item.user_name"
                        :value="item.user_id" />
                </el-select>
                <el-tree-select v-model="deptId" :data="deptOpt" :props="defaultProps" style="width: 240px;"
                    :check-strictly="true" placeholder="请选择销售部门" @change="getUser()">
                    <template #header>
                        <el-input v-model="dept_name" placeholder="搜索销售部门" style="padding: 5px"
                            @input="deptFillDebounced" />
                    </template>
                </el-tree-select>
            </div>
            <div style="float: right;margin: 10px 0px;">
                <el-button @click="orderReaslt">重置</el-button>
                <el-button type="primary" @click="orderEedit">
                    查询
                </el-button>
            </div>
        </div>
        <el-table ref="multipleTableRef" :data="orderData" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
            textAlign: 'center',
            background: '#f5f7fa',
            fontWeight: 'bold',
            position: 'sticky',
            top: 0
        }">
            <el-table-column width="55">
                <template #default="scope">
                    <el-radio class="radio" :label="scope.row" v-model="currentRow">&emsp;&emsp;&emsp;</el-radio>
                </template>
            </el-table-column>
            <el-table-column property="sale_order_code" label="销售编号" width="160" />
            <el-table-column property="sale_order_name" label="销售名称" width="160" />
            <el-table-column property="sale_order_status" label="单据状态" width="80">
                <template #default="scope">
                    <span>{{ scope.row.sale_order_status == 0 ? '待出库' : scope.row.sale_order_status == 1 ? '部分出库'
                        : scope.row.sale_order_status == 2 ? '全部出库' : scope.row.sale_order_status == 3 ? '部分退货'
                        :"未知状态"}}</span>
                </template>
            </el-table-column>
            <el-table-column property="customer_name" label="客户名称" />
            <el-table-column property="sale_order_dept_Id" label="销售部门">
                <template #default="scope">
                    <span>{{ deptValue(scope.row.sale_order_dept_id) }}</span>
                </template>
            </el-table-column>
            <el-table-column property="sale_order_rep_id" label="销售负责人">
                <template #default="scope">
                    <span>{{ userValue(scope.row.sale_order_rep_id) }}</span>
                </template>
            </el-table-column>
            <el-table-column property="sale_order_total_qty" label="销售数量" />
            <el-table-column property="sale_order_total_price" label="销售金额" />
        </el-table>
        <br>
        <div style="text-align: center;display: flex; justify-content: center;">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small" />
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleConfirmColse">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelection">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="proDetailsTableVisible" width="1010" title="添加销售明细">
        <hr>
        <div style="margin: 10px 0px;">
            <div style="float: left;margin: 10px 0px;">
                <el-input v-model="productName" style="width: 240px;margin-right: 20px;" placeholder="请输入产品编号/名称" />
                <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                    <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                        :value="item.dict_value" />
                </el-select>
            </div>
            <div style="float: right;margin: 10px 0px;">
                <el-button @click="detalisReaslt">重置</el-button>
                <el-button type="primary" @click="detailsEedit">
                    查询
                </el-button>
            </div>
        </div>
        <el-table ref="multipleTableDetailsRef" :data="detailsData" :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" @selection-change="handleSelectedChange">
            <el-table-column type="selection" width="55" :selectable="isDisabled" />
            <el-table-column prop="pro_name" label="产品名称" />
            <el-table-column prop="pro_code" label="产品编号" width="160" />
            <el-table-column prop="pro_brand" label="品牌" width="100" />
            <el-table-column prop="pro_model" label="规格型号" />
            <el-table-column prop="measure_id" label="单位" width="70">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.measure_id) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="pro_sale_qty" label="销售数量" />
            <el-table-column prop="pro_sale_price" label="销售单价" />
            <el-table-column prop="pro_outbound_qty" label="已出库" />
            <el-table-column prop="unshipped_qty" label="未出库" />
        </el-table>
        <br>
        <div style="text-align: center;display: flex; justify-content: center;">
            <el-pagination v-model:current-page="detailsCurrentPage" v-model:page-size="detailsPageSize"
                :page-sizes="[5, 10, 20, 50]" :small="false" :background="true"
                layout="total, sizes, prev, pager, next, jumper" :total="detailsPageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small" />
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleConfirmDetailsClose">取消</el-button>
                <el-button type="primary" @click="handleConfirmDetailsSelection">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, inject, watch, toRaw, computed } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { ElMessage, ElLoading } from 'element-plus';
import { debounce } from 'lodash';
export default {
    setup() {
        const sales_Return = reactive({
            sale_Return_Code: "",//销售出库编号
            warehouse_code: "",//出库仓库编号
            warehouse_name: "",//出库仓库名称
            zone_code: "",//出库库区编号
            zone_name: "",//出库库区名称
            location_code: "",//出库库位编号
            location_name: "",//出库库位编号
            customer_Name: "",//客户名称
            customer_Code: "",//客户编号
            contacts_Name: "",//联系人名称
            contacts_Phone: "",//联系人电话/联系方式
            sale_Return_Store_Time: "",//入库时间
            sale_Return_Rep_Id: "",//入库员
            sale_Return_Dept_Id: "",//入库员所属部门
            sale_Order_Name: "",//销售订单名称
            sale_Order_Code: "",//销售订单编号
            sale_Order_Rep_Id: "",//销售负责人
            sale_Order_Dept_Id: "",//负责人部门
            sale_Return_Status: "",//入库状态
            sale_Return_Reason: ""//退货原因
        })
        const ruleFormRef = ref(null)
        const rules = reactive({
            sale_Return_Store_Time: [
                { required: true, message: "入库日期不能为空", trigger: ["blur", "change"] },
            ], warehouse_code: [
                { required: true, message: "入库仓库不能为空", trigger: ["blur", "change"] },
            ], zone_code: [
                { required: true, message: "入库库区不能为空", trigger: ["blur", "change"] },
            ], location_code: [
                { required: true, message: "入库库位不能为空", trigger: ["blur", "change"] },
            ], sale_Return_Dept_Id: [
                { required: true, message: "入库部门不能为空", trigger: ["blur", "change"] },
            ], sale_Return_Rep_Id: [
                { required: true, message: "入库员不能为空", trigger: ["blur", "change"] },
            ], sale_Order_Name: [
                { required: true, message: "销售订单不能为空", trigger: ["blur", "change"] },
            ], sale_Return_Reason: [
                { required: true, message: "退货原因不能为空", trigger: ["blur", "change"] },
            ]
        });
        const Weahouse = ref([]);//仓库信息
        const Warhouse_zone = ref([]);//库区信息
        const userOptions = ref([])//用户信息
        const deptOptions = ref([])//部门信息
        const proSaleTableVisible = ref(false)
        const proDetailsTableVisible = ref(false)
        const deptName = ref("")
        const userName = ref("")
        const orderData = ref([])
        const currentPage = ref(1)
        const pageSize = ref(5)
        const pageCount = ref(0)
        const detailsCurrentPage = ref(1)
        const detailsPageSize = ref(5)
        const detailsPageCount = ref(0)
        const productName = ref("")
        const dict_code = ref("")
        const userOpt = ref([])
        const currentRow = ref(null)
        const proData = ref()
        const orderCode = ref("")//记录用户输入的销售单号
        const orderStatus = ref("")//记录用户选择的单据状态
        const customerName = ref("")//记录用户选择的客户
        const repId = ref("")//记录用户选择的销售负责人
        const deptId = ref("")//记录用户选择的销售部门
        const customerOptons = ref([])
        const customer_Name = ref("")
        const user_name = ref("")
        const deptOpt = ref([])
        const dept_name = ref("")
        const detailsData = ref([])
        const measureOptios = ref([])
        const Warehouse_location = ref([])//库位信息
        const selectedTable = ref(null)//表格引用
        const multipleTableDetailsRef = ref(null)//明细表格引用
        const selectedDetailesRows = ref([]);//存储选中的数据
        const selectedDetailsData = ref([]); // 最终确认选择的数据
        const sale_return_total_qty = ref(0)//记录本次退货总数量
        const pro_return_total_price = ref(0)//记录本次退货总金额
        const return_status = ref('待退货')//记录本次出库状态
        const router = useRouter()
        const pro_sale_num = computed(() => {
            return detailsData.value.reduce((total, row) => {
                return total + (Number(row.pro_sale_qty) || 0)
            }, 0)
        })
        const stockData = ref([])
        const statusOpt = ref([{
            label: "待出库",
            value: "0"
        }, {
            label: "部分出库",
            value: "1"
        }, {
            label: "全部出库",
            value: "2"
        }, {
            label: "部分退货",
            value: "3"
        }])

        onMounted(() => {
            getMeasure()
            userFill()
            deptFill()
            getCustomer()
            // WeahousesSelect()
            getUser()
            getDept()
            orderFill()
            orderCount()
        })

        watch(selectedDetailsData, (newVal) => {
            //每次计算时清空累加
            sale_return_total_qty.value = 0
            pro_return_total_price.value = 0
            return_status.value = ''
            let pro_Return_Qty = 0//记录待出库总数量
            let pro_sale_qty = 0//记录出库总数量
            newVal.forEach(row => {

                if (isNaN(Number(row.pro_Return_Qty))) {
                    ElMessage.warning('退货数量必须是数字');
                    row.pro_Return_Qty = 0;
                }

                if (row.pro_Return_Qty > row.pro_sale_qty) {
                    ElMessage.warning('退货数量不能大于销售库数量');
                    row.pro_Return_Qty = row.pro_sale_qty
                }

                sale_return_total_qty.value += Number(row.pro_Return_Qty)
                pro_return_total_price.value += Number(row.pro_Return_Price)
                pro_Return_Qty += Number(row.pro_Return_Qty)
                pro_sale_qty += Number(row.pro_sale_qty)
                row.pro_Return_Price = (Number(row.pro_Return_Qty || 0) * Number(row.pro_sale_price || 0)).toFixed(2);
            });

            if (pro_sale_num.value === 0) {
                return_status.value = '待退货'
                sales_Return.sale_Return_Status = 0
            } else {
                return_status.value = pro_Return_Qty == pro_sale_num.value ? '全部退货' : '部分退货'
                sales_Return.sale_Return_Status = pro_Return_Qty == pro_sale_num.value ? 2 : 1
            }
        }, { deep: true });


        // 查询仓库信息
        // function WeahousesSelect() {
        //     axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
        //         headers: {
        //             'Authorization': 'Bearer ' + localStorage.getItem('token')
        //         }
        //     }).then((res) => {
        //         Weahouse.value = res.data;
        //     }).catch((res) => {
        //         console.log(res)
        //     })
        // }

        // 选择入库仓库事件触发
        // const handleSelectChange = (selectedValue) => {
        //     const selectedItem = Weahouse.value.find(item => item.warehouse_code === selectedValue);
        //     sales_Return.warehouse_name = selectedItem.warehouse_name;

        //     // 根据选择的仓库编码去给库位赋值
        //     axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
        //         params: {
        //             warehouse_code: selectedValue
        //         }, headers: {
        //             authorization: `Bearer ${localStorage.getItem('token')}`
        //         }
        //     }).then((result) => {
        //         Warhouse_zone.value = result.data;
        //     })
        // };

        // //选择入库库位时触发
        // const handleSzone = (value) => {
        //     const selectedItemzone = Warhouse_zone.value.find(item => item.zone_code == value)
        //     sales_Return.zone_name = selectedItemzone.zone_name;

        //     axios.get("http://localhost:5181/api/Db_warehouse_location/warehouse_location", {
        //         params: {
        //             zone_code: value
        //         }, headers: {
        //             authorization: `Bearer ${localStorage.getItem('token')}`
        //         }
        //     }).then((result) => {
        //         Warehouse_location.value = result.data;
        //     }).catch((err) => {
        //         console.info(err)
        //     })
        // }

        const handleLocationChange = (value, row) => {
            // 找到选中的库位
            const selectedLocation = Warehouse_location.value.find(item => item.location_code == value);
            // 更新当前行的库位信息
            if (selectedLocation) {
                row.location_code = selectedLocation.location_code;
                row.location_name = selectedLocation.location_name;
            } else {
                row.location_code = "";
                row.location_name = "";
            }
        };

        //防抖函数0.5秒后进行查询
        const getDeptDebounced = debounce(getDept, 500);
        function getDept() {
            axios.get("http://localhost:5181/api/Dept/Get_Dept_Trees", {
                params: {
                    name: deptName.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                deptOptions.value = convertToTreeOptions(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        function deptValue(row) {
            if (!row) return "无";
            // 直接从已加载的deptOptions中查找
            const found = findDeptById(deptOptions.value, row);
            return found ? found.label : "无";
        }

        // 递归查找部门
        function findDeptById(nodes, id) {
            for (const node of nodes) {
                if (node.value === id) return node;
                if (node.children) {
                    const found = findDeptById(node.children, id);
                    if (found) return found;
                }
            }
            return null;
        }

        const userFillDebounced = debounce(userFill, 500)
        function userFill() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                params: {
                    dept: 0,
                    name: user_name.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOpt.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        const deptFillDebounced = debounce(deptFill, 500);
        function deptFill() {
            axios.get("http://localhost:5181/api/Dept/Get_Dept_Trees", {
                params: {
                    name: dept_name.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                deptOpt.value = convertToTreeOptions(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        function userValue(row) {
            if (!row) return "无";
            const parentUser = userOpt.value.find((user) => user.user_id == row)
            return parentUser ? parentUser.user_name : "无"
        }

        const getUserDebounced = debounce(getUser, 500);
        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                params: {
                    dept: sales_Return.sale_Return_Dept_Id,
                    name: userName.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        //把二维数据转换为结构数据
        const convertToTreeOptions = (items) => {
            return items.map(item => ({
                value: item.dept_id,
                label: item.dept_name,
                children: item.children && item.children.length > 0
                    ? convertToTreeOptions(item.children)
                    : []
            }))
        }

        //查询计量单位
        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data
                measureOptios.value = [{
                    dict_value: "0", dict_label: "请选择单位"
                }, ...result.data]
            }).catch((err) => {
                console.info(err)
            });
        }

        //根据计量单位id返回计量单位名称
        function measureValue(row) {
            if (!row) return "无";
            const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        function showOrderDialog() {
            proSaleTableVisible.value = true
        }

        //查询销售订单信息
        function orderFill() {
            axios.get("http://localhost:5181/api/Sinv_Sale_Order/Sinv_Sale_OrderSelectFill", {
                params: {
                    currentPage: currentPage.value,
                    pageSize: pageSize.value,
                    orderCode: orderCode.value,
                    status: orderStatus.value == "" ? -1 : Number(orderStatus.value),
                    customerName: customerName.value,
                    rep_id: repId.value == "" ? 0 : Number(repId.value),
                    dept_id: deptId.value == "" ? 0 : Number(deptId.value)
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                orderData.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        //查询销售订单总数
        function orderCount() {
            axios.get("http://localhost:5181/api/Sinv_Sale_Order/Sinv_Sale_OrderSelectFillCount", {
                params: {
                    orderCode: orderCode.value,
                    status: orderStatus.value == "" ? -1 : Number(orderStatus.value),
                    customerName: customerName.value,
                    rep_id: repId.value == "" ? 0 : Number(repId.value),
                    dept_id: deptId.value == "" ? 0 : Number(deptId.value)
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                pageCount.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        const getCustomerDebounced = debounce(getCustomer, 500)
        //查询客户信息
        function getCustomer() {
            axios.get("http://localhost:5181/api/Sinv_Customer/Sinv_CustomerByName", {
                params: {
                    name: customer_Name.value
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                customerOptons.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function handleSizeChange(val) {
            pageSize.value = val;
            orderFill();
        }

        function handleCurrentChange(val) {
            currentPage.value = val;
            orderFill();
        }

        //点击确定获取销售订单信息
        function handleConfirmSelection() {
            selectedDetailsData.value = []
            if (currentRow.value) {
                proData.value = currentRow.value
                sales_Return.sale_Order_Code = proData.value.sale_order_code
                sales_Return.sale_Order_Name = proData.value.sale_order_name
                sales_Return.customer_Name = proData.value.customer_name
                sales_Return.customer_Code = proData.value.customer_code
                sales_Return.contacts_Name = proData.value.contacts_name
                sales_Return.contacts_Phone = proData.value.contacts_phone
                sales_Return.sale_Order_Rep_Id = proData.value.sale_order_rep_id
                sales_Return.sale_Order_Dept_Id = proData.value.sale_order_dept_id
                proSaleTableVisible.value = false
                fillSalesDetails()
                fillSalesDetailsCount()
                currentRow.value = null
            } else {
                ElMessage.warning('请选择要出库的销售订单数据');
                return;
            }
        }

        //条件查询按钮
        function orderEedit() {
            orderFill()
            orderCount()
        }

        //重置按钮
        function orderReaslt() {
            orderCode.value = ""
            orderStatus.value = ""
            customerName.value = ""
            repId.value = ""
            deptId.value = ""
            orderFill()
            orderCount()
        }

        //取消按钮
        function handleConfirmColse() {
            orderCode.value = ""
            orderStatus.value = ""
            customerName.value = ""
            repId.value = ""
            deptId.value = ""
            proSaleTableVisible.value = false
        }

        //添加销售明细按钮
        function detailstAdd() {
            proDetailsTableVisible.value = true
        }

        //取消销售明细按钮
        function handleConfirmDetailsClose() {
            productName.value = ""
            dict_code.value = ""
            proDetailsTableVisible.value = false
        }

        //根据销售订单编号获取对应销售订单明细
        async function fillSalesDetails() {
            try {
                const result = await axios.get("http://localhost:5181/api/Sinv_Sale_Order/GetSinv_Sale_Order_Details", {
                    params: {
                        currentPage: detailsCurrentPage.value,
                        pageSize: detailsPageSize.value,
                        code: sales_Return.sale_Order_Code,
                        productCode: productName.value,
                        measureId: dict_code.value == "" ? 0 : dict_code.value
                    },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });

                // 加载库存数据
                await productFill();

                // 创建全局仓库和库位的 Map
                const globalWarehouseMap = new Map();

                // 处理数据：添加默认值保护，移除多余的 async
                detailsData.value = result.data.map((item) => {

                    // 根据产品编号过滤库存数据
                    const stockItems = stockData.value.filter(stock =>
                        stock.pro_code === item.pro_code
                    );

                    // 处理仓库去重
                    const warehouseMap = new Map();
                    stockItems.forEach(stock => {
                        const key = `${stock.warehouse_Code}-${stock.warehouse_Name}`;

                        // 本地去重
                        if (!warehouseMap.has(key)) {
                            warehouseMap.set(key, {
                                warehouse_code: stock.warehouse_Code,
                                warehouse_name: stock.warehouse_Name
                            });
                        }

                        // 全局去重
                        if (!globalWarehouseMap.has(key)) {
                            globalWarehouseMap.set(key, {
                                warehouse_code: stock.warehouse_Code,
                                warehouse_name: stock.warehouse_Name
                            });
                        }
                    });

                    return {
                        ...item,
                        unshipped_qty: (Number(item.pro_sale_qty || 0) - Number(item.pro_outbound_qty || 0)) - Number(item.pro_return_qty || 0),
                        pro_Return_Qty: item.pro_Return_Qty || 0,
                        pro_Return_Price: (Number(item.pro_Return_Qty || 0) * Number(item.pro_sale_price || 0)).toFixed(2)
                    }
                });
                Weahouse.value = Array.from(globalWarehouseMap.values());
            } catch (err) {
                console.error("请求失败:", err);
            }
        }

        async function productFill() {
            return axios.get("http://localhost:5181/api/Db_warehouse/GetInv_Stock", {
                headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
            }).then((result) => {
                stockData.value = result.data;
                return result.data; // 返回数据供后续使用
            }).catch(console.error);
        }

        // 选择入库仓库事件触发
        const handleSelectChange = (selectedValue) => {
            const selectedItem = Weahouse.value.find(item => item.warehouse_code === selectedValue);
            sales_Return.warehouse_name = selectedItem.warehouse_name;

            // 1. 过滤当前选中仓库的库存记录
            const currentWarehouseStocks = stockData.value.filter(
                stock => stock.warehouse_Code === selectedValue
            );

            // 2. 使用Map对库区去重（确保唯一性）
            const zoneMap = new Map();
            currentWarehouseStocks.forEach(stock => {
                // 确保库存记录中存在库区数据
                if (stock.zone_Code && stock.zone_Name) {
                    const zoneKey = `${stock.zone_Code}-${stock.zone_Name}`;
                    if (!zoneMap.has(zoneKey)) {
                        zoneMap.set(zoneKey, {
                            zone_code: stock.zone_Code,
                            zone_name: stock.zone_Name
                        });
                    }
                }
            });

            // 3. 转换为数组并更新库区数据
            Warhouse_zone.value = Array.from(zoneMap.values());
        };

        //选择入库库位时触发
        const handleSzone = (value) => {
            const selectedItemzone = Warhouse_zone.value.find(item => item.zone_code == value)
            sales_Return.zone_name = selectedItemzone.zone_name;

            // 1. 过滤当前选中仓库的库存记录
            const currentWarehouseStocks = stockData.value.filter(
                stock => stock.zone_Code === value
            );

            // 2. 使用Map对库区去重（确保唯一性）
            const locationMap = new Map();
            currentWarehouseStocks.forEach(stock => {
                // 确保库存记录中存在库区数据
                if (stock.location_Code && stock.location_Name) {
                    const locationKey = `${stock.location_Code}-${stock.location_Name}`;
                    if (!locationMap.has(locationKey)) {
                        locationMap.set(locationKey, {
                            location_code: stock.location_Code,
                            location_name: stock.location_Name
                        });
                    }
                }
            });

            // 3. 转换为数组并更新库区数据
            Warehouse_location.value = Array.from(locationMap.values());
            // axios.get("http://localhost:5181/api/Db_warehouse_location/warehouse_location", {
            //     params: {
            //         zone_code: value
            //     }, headers: {
            //         authorization: `Bearer ${localStorage.getItem('token')}`
            //     }
            // }).then(async (result) => {
            //     Warehouse_location.value = result.data;
            //加载库存数据
            // await productFill()

            // // 3. 处理数据：为每个订单明细添加库位选项
            // result.data.map((item) => {
            //     // 根据产品编号过滤库存数据
            //     const stockItems = stockData.value.filter(stock =>
            //         stock.pro_code === item.pro_code && stock.zone_Code === value
            //     );
            //     const Warehouse_locationMap = new Map();
            //     stockItems.forEach(stock => {
            //         const key = `${stock.zone_Code}-${stock.zone_Name}`;
            //         console.info(key)
            //         // 如果不存在该键才添加
            //         if (!Warehouse_locationMap.has(key)) {
            //             Warehouse_locationMap.set(key, {
            //                 zone_code: stock.zone_Code,
            //                 zone_name: stock.zone_Name
            //             });
            //         }
            //     });

            //     // 最后一次性添加所有唯一值
            //     Warehouse_location.value = Array.from(Warehouse_locationMap.values());
            // })
            // }).catch((err) => {
            //     console.info(err)
            // })
        }

        //查询销售订单明细总数
        function fillSalesDetailsCount() {
            axios.get("http://localhost:5181/api/Sinv_Sale_Order/GetSinv_Sale_Order_DetailsCount", {
                params: {
                    code: sales_Return.sale_Order_Code,
                    productCode: productName.value,
                    measureId: dict_code.value == "" ? 0 : dict_code.value
                }, headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
            }).then((result) => {
                detailsPageCount.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function detailsEedit() {
            fillSalesDetails()
            fillSalesDetailsCount()
        }

        function detalisReaslt() {
            productName.value = ""
            dict_code.value = ""
            fillSalesDetails()
            fillSalesDetailsCount()
        }

        //表格选择变化时处理数据
        const handleSelectedChange = (val) => {
            selectedDetailesRows.value = val;
        };

        //点击确定保存选中的销售明细数据
        const handleConfirmDetailsSelection = () => {
            const newItems = selectedDetailesRows.value.map(item => ({
                ...item,
                location_code: ""
            }));

            // 合并数据（去重）
            selectedDetailsData.value = [
                ...selectedDetailsData.value,
                ...newItems.filter(newItem =>
                    !selectedDetailsData.value.some(existItem =>
                        existItem.pro_code === newItem.pro_code
                    )
                )
            ];
            multipleTableDetailsRef.value?.clearSelection();
            handleConfirmDetailsClose();
        }

        //判断以添加过的产品数据不能再次添加
        const isDisabled = (row) => {
            return !selectedDetailsData.value.some(item => item.pro_code === row.pro_code);
        };

        //移除选中的table控件数据
        const productDel = () => {
            if (selectedDetailesRows.value.length === 0) {
                ElMessage.warning('请先选择要移除的数据');
                return;
            }

            // 根据pro_code过滤要保留的数据
            const selectedCodes = selectedDetailesRows.value.map(item => item.pro_code);
            selectedDetailsData.value = selectedDetailsData.value.filter(
                item => !selectedCodes.includes(item.pro_code)
            );

            selectedTable.value?.clearSelection();
            selectedDetailesRows.value = [];
        };

        //获取编号
        const validateLocations = () => {
            return selectedDetailsData.value.every(item => {
                return item.location_code && item.location_name;
            });
        };


        //添加销售出库信息
        function handleAdd() {
            // returnAdd()
            ruleFormRef.value.validate(async (valid, fields) => {
                if (valid) {
                    if (selectedDetailsData.value.length > 0) {
                        // if (validateLocations()) {
                        obtainCode().then(() => {
                            returnAdd()
                        }).catch((err) => {
                            console.info(err)
                        });
                        // } else {
                        //     ElMessage.warning('请为所有产品选择库位');
                        //     return;
                        // }
                    } else {
                        ElMessage.warning('请选择要添加的产品数据');
                        return;
                    }
                }
            })
        }

        //获取销售出库编号
        function obtainCode() {
            return axios.get("http://localhost:5181/api/DJBH/DJBH", {
                params: {
                    en_code: 13
                }
            }).then((result) => {
                sales_Return.sale_Return_Code = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function returnAdd() {
            const loadingInstance = ElLoading.service({
                lock: true,
                text: '正在添加中...',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            const sinv_Sale_Return_DetailsAddDto = selectedDetailsData.value.map(item => ({
                sale_order_details_id: item.sale_order_details_id,
                pro_Name: item.pro_name,
                pro_Code: item.pro_code,
                pro_Brand: item.pro_brand,
                pro_Model: item.pro_model,
                measure_Id: item.measure_id,
                pro_Sale_Qty: item.pro_sale_qty,
                pro_Return_Qty: item.pro_Return_Qty,
                pro_Return_Price: item.pro_Return_Price,
                pro_Store_Qty: item.pro_Return_Qty
            }))
            const saleReturnWithDetailsDto = {
                sinv_Sale_ReturnAddDto: {
                    sale_Return_Store_Time: sales_Return.sale_Return_Store_Time,
                    sale_Return_Code: sales_Return.sale_Return_Code,
                    sale_Order_Name: sales_Return.sale_Order_Name,
                    sale_Order_Code: sales_Return.sale_Order_Code,
                    customer_Name: sales_Return.customer_Name,
                    customer_Code: sales_Return.customer_Code,
                    contacts_Name: sales_Return.contacts_Name,
                    contacts_Phone: sales_Return.contacts_Phone,
                    sale_Order_Rep_Id: Number(sales_Return.sale_Order_Rep_Id),
                    sale_Order_Dept_Id: Number(sales_Return.sale_Order_Dept_Id),
                    sale_Return_Audit_Status: '0',
                    warehouse_Code: sales_Return.warehouse_code,
                    Warehouse_Name: sales_Return.warehouse_name,
                    zone_Code: sales_Return.zone_code,
                    zone_Name: sales_Return.zone_name,
                    sale_Return_Reason: sales_Return.sale_Return_Reason,
                    sale_Return_Status: sales_Return.sale_Return_Status,
                    sale_Return_Rep_Id: Number(sales_Return.sale_Return_Rep_Id),
                    sale_Return_Dept_Id: Number(sales_Return.sale_Return_Dept_Id),
                    create_By: localStorage.getItem('userLName'),//创建人
                    create_Time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),//创建时间
                    del_Flag: '0'
                },
                sinv_Sale_Return_DetailsAddDtos: [...sinv_Sale_Return_DetailsAddDto]
            }
            axios.post("http://localhost:5181/api/Sinv_Sale_Return/Sinv_Sale_ReturnAdd", saleReturnWithDetailsDto, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: '销售退货订单添加成功！'
                    });
                    handleClose()
                } else {
                    ElMessage({
                        type: 'danger',
                        message: '销售退货订单添加失败！'
                    });
                }
            }).catch((err) => {
                console.info(err)
            }).finally(() => {
                loadingInstance.close();
            })
        }

        const closeTab = inject('closeTab'); // 注入关闭方法
        function handleClose() {
            const targetPath = "/main/Sinv/SalesReturn";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法
            }

            // 添加目标标签页（如果不存在）
            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "销售退货",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页
            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        }

        return {
            sales_Return, Weahouse, handleSelectChange, Warhouse_zone, userOptions, deptOptions, showOrderDialog, proSaleTableVisible,
            deptName, userName, getUserDebounced, getDeptDebounced, getUser, orderData, currentPage, pageSize, pageCount, handleSizeChange,
            handleCurrentChange, deptValue, userValue, userOpt, currentRow, handleConfirmSelection, orderCode, orderStatus, customerName, repId
            , deptId, customerOptons, customer_Name, getCustomerDebounced, user_name, userFillDebounced, deptFillDebounced, dept_name, deptOpt,
            statusOpt, orderEedit, orderReaslt, proData, detailsData, measureOptios, measureValue, Warehouse_location, handleSzone, selectedTable,
            handleSelectedChange, proDetailsTableVisible, detailsCurrentPage, detailsPageCount, detailsPageSize, productName, dict_code,
            detailstAdd, detailsEedit, detalisReaslt, handleConfirmColse, handleConfirmDetailsClose, multipleTableDetailsRef, selectedDetailesRows,
            selectedDetailsData, handleConfirmDetailsSelection, isDisabled, productDel, sale_return_total_qty, pro_return_total_price, return_status,
            rules, ruleFormRef, handleAdd, handleLocationChange, handleClose
        }
    }
}
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}
</style>